/**
 * 模块管理器 Composable
 * 提供模块管理的响应式接口
 */
import { ref, readonly, onUnmounted } from 'vue'
import { moduleManager } from '../dynamic/ModuleManager'
import type { 
  DynamicModule, 
  ModuleLoadState, 
  ModulePerformanceMetrics,
  ModuleErrorInfo,
  ModuleRegistrationOptions,
  ModuleLoadOptions,
  ModuleUnloadOptions
} from '../dynamic/types'

/**
 * 模块管理器 Composable
 * 
 * 功能：
 * 1. 提供模块管理的响应式接口
 * 2. 封装模块管理器的功能
 * 3. 提供类型安全的方法调用
 * 4. 自动清理事件监听器
 */
export function useModuleManager() {
  // 响应式状态
  const modules = ref<DynamicModule[]>([])
  const loadedModules = ref<DynamicModule[]>([])
  const loadingModules = ref<Set<string>>(new Set())
  const errorModules = ref<Map<string, string>>(new Map())
  const performanceMetrics = ref<Map<string, ModulePerformanceMetrics>>(new Map())
  const errorHistory = ref<Map<string, ModuleErrorInfo[]>>(new Map())

  // 事件监听器映射
  const eventListeners = new Map<string, Function[]>()

  /**
   * 注册模块
   */
  const registerModule = async (module: DynamicModule, options?: ModuleRegistrationOptions) => {
    await moduleManager.registerModule(module, options)
    await refreshModulesList()
  }

  /**
   * 加载模块
   */
  const loadModule = async (moduleId: string, options?: ModuleLoadOptions) => {
    loadingModules.value.add(moduleId)
    errorModules.value.delete(moduleId)

    try {
      const component = await moduleManager.loadModule(moduleId, options)
      await refreshModulesList()
      return component
    } catch (error) {
      errorModules.value.set(moduleId, error instanceof Error ? error.message : 'Unknown error')
      throw error
    } finally {
      loadingModules.value.delete(moduleId)
    }
  }

  /**
   * 卸载模块
   */
  const unloadModule = async (moduleId: string, options?: ModuleUnloadOptions) => {
    await moduleManager.unloadModule(moduleId, options)
    await refreshModulesList()
  }

  /**
   * 重新加载模块
   */
  const reloadModule = async (moduleId: string, options?: ModuleLoadOptions) => {
    await moduleManager.reloadModule(moduleId, options)
    await refreshModulesList()
  }

  /**
   * 批量加载模块
   */
  const loadModules = async (moduleIds: string[], options?: ModuleLoadOptions) => {
    moduleIds.forEach(id => loadingModules.value.add(id))
    
    try {
      await moduleManager.loadModules(moduleIds, options)
      await refreshModulesList()
    } finally {
      moduleIds.forEach(id => loadingModules.value.delete(id))
    }
  }

  /**
   * 批量卸载模块
   */
  const unloadModules = async (moduleIds: string[], options?: ModuleUnloadOptions) => {
    await moduleManager.unloadModules(moduleIds, options)
    await refreshModulesList()
  }

  /**
   * 获取模块状态
   */
  const getModuleState = (moduleId: string): ModuleLoadState | undefined => {
    return moduleManager.getModuleState(moduleId)
  }

  /**
   * 获取模块信息
   */
  const getModule = (moduleId: string): DynamicModule | undefined => {
    return moduleManager.getModule(moduleId)
  }

  /**
   * 检查模块是否已加载
   */
  const isModuleLoaded = (moduleId: string): boolean => {
    return moduleManager.isModuleLoaded(moduleId)
  }

  /**
   * 获取模块性能指标
   */
  const getPerformanceMetrics = (moduleId: string): ModulePerformanceMetrics | undefined => {
    return moduleManager.getPerformanceMetrics(moduleId)
  }

  /**
   * 获取模块错误历史
   */
  const getErrorHistory = (moduleId: string): ModuleErrorInfo[] => {
    return moduleManager.getErrorHistory(moduleId)
  }

  /**
   * 获取系统统计信息
   */
  const getSystemStats = () => {
    return moduleManager.getSystemStats()
  }

  /**
   * 清理系统
   */
  const cleanup = async () => {
    await moduleManager.cleanup()
    await refreshModulesList()
  }

  /**
   * 注册事件监听器
   */
  const on = (event: string, handler: Function) => {
    if (!eventListeners.has(event)) {
      eventListeners.set(event, [])
    }
    eventListeners.get(event)!.push(handler)
    moduleManager.on(event, handler)
  }

  /**
   * 移除事件监听器
   */
  const off = (event: string, handler: Function) => {
    const listeners = eventListeners.get(event)
    if (listeners) {
      const index = listeners.indexOf(handler)
      if (index > -1) {
        listeners.splice(index, 1)
      }
      if (listeners.length === 0) {
        eventListeners.delete(event)
      }
    }
    moduleManager.off(event, handler)
  }

  /**
   * 刷新模块列表
   */
  const refreshModulesList = async () => {
    try {
      // 获取所有模块
      modules.value = moduleManager.getAllModules()
      
      // 获取已加载的模块
      loadedModules.value = moduleManager.getLoadedModules()
      
      // 更新加载中的模块
      const newLoadingModules = new Set<string>()
      modules.value.forEach(module => {
        const state = moduleManager.getModuleState(module.id)
        if (state?.status === 'loading') {
          newLoadingModules.add(module.id)
        }
      })
      loadingModules.value = newLoadingModules
      
      // 更新错误模块
      const newErrorModules = new Map<string, string>()
      modules.value.forEach(module => {
        const state = moduleManager.getModuleState(module.id)
        if (state?.status === 'error' && state.error) {
          newErrorModules.set(module.id, state.error)
        }
      })
      errorModules.value = newErrorModules
      
      // 更新性能指标
      const newPerformanceMetrics = new Map<string, ModulePerformanceMetrics>()
      modules.value.forEach(module => {
        const metrics = moduleManager.getPerformanceMetrics(module.id)
        if (metrics) {
          newPerformanceMetrics.set(module.id, metrics)
        }
      })
      performanceMetrics.value = newPerformanceMetrics
      
      // 更新错误历史
      const newErrorHistory = new Map<string, ModuleErrorInfo[]>()
      modules.value.forEach(module => {
        const history = moduleManager.getErrorHistory(module.id)
        if (history.length > 0) {
          newErrorHistory.set(module.id, history)
        }
      })
      errorHistory.value = newErrorHistory
      
    } catch (error) {
      console.error('Failed to refresh modules list:', error)
    }
  }

  /**
   * 初始化
   */
  const initialize = async () => {
    await refreshModulesList()
    
    // 设置自动刷新
    const refreshInterval = setInterval(refreshModulesList, 30000) // 每30秒刷新一次
    
    // 组件卸载时清理
    onUnmounted(() => {
      clearInterval(refreshInterval)
      
      // 清理所有事件监听器
      eventListeners.forEach((listeners, event) => {
        listeners.forEach(handler => {
          moduleManager.off(event, handler)
        })
      })
      eventListeners.clear()
    })
  }

  /**
   * 获取模块加载状态
   */
  const getModuleLoadStatus = (moduleId: string): 'loading' | 'loaded' | 'error' | 'unloaded' => {
    if (loadingModules.value.has(moduleId)) return 'loading'
    if (errorModules.value.has(moduleId)) return 'error'
    if (loadedModules.value.some(m => m.id === moduleId)) return 'loaded'
    return 'unloaded'
  }

  /**
   * 获取模块错误信息
   */
  const getModuleError = (moduleId: string): string | undefined => {
    return errorModules.value.get(moduleId)
  }

  /**
   * 获取模块加载进度
   */
  const getModuleLoadProgress = (moduleId: string): number => {
    const state = moduleManager.getModuleState(moduleId)
    if (state?.status === 'loaded') return 100
    if (state?.status === 'loading') {
      // 简化的进度计算
      return Math.min(90, (state.retryCount || 0) * 30)
    }
    return 0
  }

  /**
   * 检查模块是否可用
   */
  const isModuleAvailable = (moduleId: string): boolean => {
    return modules.value.some(m => m.id === moduleId)
  }

  /**
   * 获取模块分类列表
   */
  const getModuleCategories = (): string[] => {
    const categories = new Set<string>()
    modules.value.forEach(module => {
      if (module.category) {
        categories.add(module.category)
      }
    })
    return Array.from(categories).sort()
  }

  /**
   * 按分类筛选模块
   */
  const getModulesByCategory = (category: string): DynamicModule[] => {
    return modules.value.filter(module => module.category === category)
  }

  /**
   * 搜索模块
   */
  const searchModules = (query: string): DynamicModule[] => {
    const lowercaseQuery = query.toLowerCase()
    return modules.value.filter(module => 
      module.name.toLowerCase().includes(lowercaseQuery) ||
      module.description.toLowerCase().includes(lowercaseQuery) ||
      module.category.toLowerCase().includes(lowercaseQuery)
    )
  }

  /**
   * 获取模块依赖图
   */
  const getModuleDependencies = (moduleId: string): string[] => {
    const module = getModule(moduleId)
    return module?.dependencies || []
  }

  /**
   * 检查模块依赖是否满足
   */
  const areModuleDependenciesSatisfied = (moduleId: string): boolean => {
    const dependencies = getModuleDependencies(moduleId)
    return dependencies.every(depId => isModuleLoaded(depId))
  }

  /**
   * 获取模块统计信息
   */
  const getModuleStats = () => {
    const totalModules = modules.value.length
    const loadedCount = loadedModules.value.length
    const loadingCount = loadingModules.value.size
    const errorCount = errorModules.value.size

    return {
      total: totalModules,
      loaded: loadedCount,
      loading: loadingCount,
      error: errorCount,
      unloaded: totalModules - loadedCount - loadingCount - errorCount,
      loadRate: totalModules > 0 ? (loadedCount / totalModules) * 100 : 0,
      errorRate: totalModules > 0 ? (errorCount / totalModules) * 100 : 0
    }
  }

  // 初始化
  initialize()

  return {
    // 响应式状态
    modules: readonly(modules),
    loadedModules: readonly(loadedModules),
    loadingModules: readonly(loadingModules),
    errorModules: readonly(errorModules),
    performanceMetrics: readonly(performanceMetrics),
    errorHistory: readonly(errorHistory),
    
    // 核心方法
    registerModule,
    loadModule,
    unloadModule,
    reloadModule,
    loadModules,
    unloadModules,
    
    // 查询方法
    getModuleState,
    getModule,
    isModuleLoaded,
    getPerformanceMetrics,
    getErrorHistory,
    getSystemStats,
    getModuleLoadStatus,
    getModuleError,
    getModuleLoadProgress,
    isModuleAvailable,
    getModuleCategories,
    getModulesByCategory,
    searchModules,
    getModuleDependencies,
    areModuleDependenciesSatisfied,
    getModuleStats,
    
    // 工具方法
    cleanup,
    refreshModulesList,
    
    // 事件方法
    on,
    off
  }
}
